<template>
  <div class="editable-cell">
        <div v-if="editable" class="editable-cell-input-wrapper">
          <a-input v-model.lazy="val" @change="handleChange" @blur="onBlur" :maxLength="maxLength"/>
          <a  v-show="isShowEditBtn" href="javascript:;" title="确认" class="" @click="check"><i class="fa fa-check" style="color: #69aa46;"></i></a>
        </div>
        <div v-else class="editable-cell-text-wrapper">
          {{ value || ' ' }}
        <a href="javascript:;" title="编辑" class="" @click="edit"><i class="fa fa-edit" style="color: #EC755D;"></i></a>
        </div>
      </div>
</template>

<script>
export default {
    name: "EditableCell",
    props: {
    text: [String,Number],
    isShowEditBtn: {
        type: Boolean,
        default: false
    },
    reg: RegExp ,
    maxLength: {
      type: Number,
      default: 9
    }
  },
  data() {
    return {
      val: this.text,
      newVal: this.text,
      editable: !this.isShowEditBtn,
    };
  },

  methods: {
    handleChange(e) {
        const {value} = e.target;
        if ((!isNaN(value))) {
            if(this.reg && this.reg.test && this.reg.test(value)){
                this.newVal = value;
                if(!this.isShowEditBtn){
                    this.$emit('editableChange', this.val);
                }
            }
        }
    },
     onBlur(e) {
      this.val = this.newVal;
    },
    check() {
        if(this.isShowEditBtn){
           this.editable = false;
        }
      this.$emit('editableChange', this.val);
    },
    edit() {
         this.editable = true;
    },
  },
  watch:{
    val:function(newVal,oldVal){
      console.log("oldVal：",oldVal,"newVal",newVal);
    }
  }
}
</script>

<style>

</style>